import {PlusOutlined} from '@ant-design/icons';
import {
  Button,
  Divider,
  message,
  Input,
  Drawer,
  InputNumber,
  Select,
  Form,
  Modal,
  Badge,
  Tooltip,
  Radio,
  Tag
} from 'antd';
import {ExclamationCircleOutlined} from '@ant-design/icons';
import React, {useState, useRef} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import PurchaseApprovalForm from './components/PurchaseApprovalForm';
import {queryRule, approve } from './service';
import PurchaseApplyForm from "@/pages/purchase/purchase-apply/components/PurchaseApplyForm";


const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [selectedRow, setSelectedRow] = useState({});
  const [formTitle, setFormTitle] = useState('采购审批');
  const [activekey, setActiveKey] = useState('tab1');
  const [approvalOperation, setApprovalOperation] = useState(2);
  const actionRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const {Option} = Select;
  const {TextArea} = Input;
  const handleUpdateModalVisible = (record) => {
    formRef.setFieldsValue({
      ...record
    })
    setSelectedRow(record)
    setFormTitle('采购审批')
    handleModalVisible(true)
  }
  const approvalOperationOnChange = (e)=> {
    setApprovalOperation(e.target.value)
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '采购编码',
      dataIndex: 'requestCode',
      tip: '采购编码是唯一的',
      copyable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={type === 'form'} placeholder={'请输入采购编码'}/>;
      }
    },
    {
      title: '物料编码',
      dataIndex: 'materialCode',
      tip: '物料编码是唯一的',
      valueType: 'input',
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={type === 'form'} />;
      }
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={type === 'form'}  maxLength={11} placeholder={'请输入物料名称'}/>;
      }
    },
    {
      title: '计量单位',
      dataIndex: 'materialUnit',
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={true} />;
      }
    },
    {
      title: '数量',
      dataIndex: 'num',
      sorter: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={true} />;
      }
    },
    {
      title: '单价',
      dataIndex: 'materialPrice',
      sorter: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={true} />;
      }
    },
    {
      title: '总价',
      dataIndex: 'totalPrice',
      sorter: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={true} suffix="元"/>;
      }
    },
    {
      title: '付款方式',
      dataIndex: 'payType',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Radio.Group disabled={true}>
          <Radio value={1}>现金</Radio>
          <Radio value={2}>月结</Radio>
        </Radio.Group>
      },
      render: (text, record) => {
        return <Tag>{text === 1 ? '现金' : '月结'}</Tag>
      }
    },
    {
      title: '月结天数',
      dataIndex: 'payDays',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={true} />;
      }
    },
    {
      title: '供应商',
      dataIndex: 'providerName',
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={true} />;
      }
    },
    {
      title: '状态',
      dataIndex: 'requestStatus',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select defaultValue={-1}>
          <Option value={-1}>全部</Option>
          <Option value={0}>草稿</Option>
          <Option value={1}>待审批</Option>
          <Option value={2}>已审批</Option>
          <Option value={3}>已驳回</Option>
        </Select>;
      },
      render: (text, record, index) => {
        return (
          <Tag color={text === 0 ? 'magenta' :
            text === 1 ? 'red' :
              text === 2 ? 'blue' : 'gold'
          }>{text === 0 ? '草稿' :
            text === 1 ? '待审批' :
              text === 2 ? '已审批' : '已驳回'}</Tag>
        )
      }
    },
    {
      title: '创建人',
      dataIndex: 'createName',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '备注',
      dataIndex: 'requestRemark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <TextArea disabled={true} />;
      }
    },
    {
      title: '审批人',
      dataIndex: 'approvalBy',
      hideInTable: true,
      hideInSearch: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select disabled={true}>
          <Option value={2}>admin</Option>
          <Option value={4}>张三</Option>
          <Option value={6}>李四</Option>
          <Option value={8}>王五</Option>
        </Select>;
      }
    },
    {
      title: '审批操作',
      dataIndex: 'approveStatus',
      hideInTable: true,
      hideInSearch: true,
      // formItemProps: {
      //   rules: [
      //     {
      //       required: true,
      //       message: '审批操作是必填项'
      //     }
      //   ],
      // },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Radio.Group value={approvalOperation} onChange={(e)=>approvalOperationOnChange(e)}>
          <Radio value={2}>通过</Radio>
          <Radio value={3}>驳回</Radio>
        </Radio.Group>;
      }
    },
    {
      title: '驳回原因',
      dataIndex: 'rejectReason',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '驳回原因是必填项'
          }
        ],
      },
      hideInForm: approvalOperation === 2? true: false
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => setRow(record)}>
          详情
        </a>,
        <Divider type="vertical" style={{display: record.requestStatus === 1? 'block': 'none'}}/>,
        <a style={{display: record.requestStatus === 1? 'block': 'none'}} onClick={() => handleUpdateModalVisible(record)}>审批</a>,
      ],
    },
  ];

  const detailColumns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '采购编码',
      dataIndex: 'requestCode',
      tip: '采购编码是唯一的',
      hideInForm: true,
      copyable: true,
    },
    {
      title: '物料编码',
      dataIndex: 'materialCode',
      tip: '物料编码是唯一的',
      valueType: 'input',
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      formItemProps: {
        rules: [
          {
            max: 10,
            message: '物料名称最大长度为10'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '物料名称是必填项'
          }
        ],
      },
    },
    {
      title: '计量单位',
      dataIndex: 'materialUnit',
      hideInSearch: true,
    },
    {
      title: '数量',
      dataIndex: 'num',
      sorter: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '数量是必填项'
          }
        ],
      },
    },
    {
      title: '单价',
      dataIndex: 'materialPrice',
      sorter: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '单价是必填项'
          }
        ],
      },
    },
    {
      title: '总价',
      dataIndex: 'totalPrice',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '付款方式',
      dataIndex: 'payType',
      hideInSearch: true,
      hideInTable: true,
      render: (text, record) => {
        return <Tag>{text === 1 ? '现金' : '月结'}</Tag>
      }
    },
    {
      title: '月结天数',
      dataIndex: 'payDays',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '供应商',
      dataIndex: 'providerName',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'requestStatus',
      sorter: true,
      hideInForm: true,
      render: (text, record, index) => {
        return (
          <Tag color={text === 0 ? 'magenta' :
            text === 1 ? 'red' :
              text === 2 ? 'blue' : 'gold'
          }>{text === 0 ? '草稿' :
            text === 1 ? '待审批' :
              text === 2 ? '已审批' : '已驳回'}</Tag>
        )
      }
    },
    {
      title: '创建人',
      dataIndex: 'createName',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '备注',
      dataIndex: 'requestRemark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '审批人',
      dataIndex: 'approvalName',
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '驳回原因',
      dataIndex: 'rejectReason',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true,
      hideInForm: true,
    },
  ];

  const renderBadge = (count, active = false) => {
    return (
      <Badge
        // count={count}
        style={{
          marginTop: -2,
          marginLeft: 4,
          color: active ? '#1890FF' : '#999',
          backgroundColor: active ? '#E6F7FF' : '#eee',
        }}
      />
    );
  };

  const handleApproval = async (fields) => {
    const hide = message.loading('正在提交');

    try {
      hide();
      await approve({...fields}).then((res) => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success(res.message);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
          return false;
        }
        return true;
      });
    } catch (error) {
      hide();
      message.error('提交失败请重试！');
      return false;
    }
  };

  const onSubmit = async () => {
    formRef.validateFields().then(value => {
      const param = value;
      param.requestId = selectedRow.requestId
      param.approveStatus = approvalOperation
      const success = handleApproval(param)

      if (success) {
        handleModalVisible(false);
      }
    })

  }
  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="requestCode"
        search={{
          labelWidth: 120,
        }}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activekey,
            items: [
              {
                key: 'tab1',
                label: <span>待审批{renderBadge(99, activekey === 'tab1')}</span>,
              },
              {
                key: 'tab2',
                label: <span>已审批{renderBadge(30, activekey === 'tab2')}</span>,
              }
            ],
            onChange: (key) => {
              setActiveKey(key);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            },
          },
        }}
        request={ async (params, sorter, filter) => {
          const param =  activekey === 'tab1'?{
            ...params,
            pageNum: params.current,
            requestStatus: 1,
            approvalBy: 8
          }:{
            ...params,
            pageNum: params.current,
            requestStatuses: '2,3',
            approvalBy: 8
          };
          if (param.requestStatus === -1) {
            param.requestStatus = null;
          }
          const res = await queryRule(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}

      />
      <PurchaseApprovalForm title={formTitle} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}
                            onSubmit={() => onSubmit()}>
        <ProTable
          onSubmit={async (status) => {
            const success = await onSubmit(status);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{
            form: formRef,
            layout: 'horizontal',
            labelAlign: 'left'
          }}
          rowKey="key"
          type="form"
          columns={columns}
        />
      </PurchaseApprovalForm>
      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.requestCode && (
          <ProDescriptions
            column={2}
            title={row?.requestCode}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.requestCode,
            }}
            columns={detailColumns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
